package com.ppc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ppc.constant.MessageConstant;
import com.ppc.context.BaseContext;
import com.ppc.entity.File;
import com.ppc.entity.Recording;
import com.ppc.entity.WorkerHandInResult;
import com.ppc.exception.BaseException;
import com.ppc.exception.FileException;
import com.ppc.mapper.user.FileMapper;
import com.ppc.mapper.worker.WorkerMapper;
import com.ppc.mapper.worker.WorkerTaskMapper;
import com.ppc.result.PageResult;
import com.ppc.service.WorkerTaskService;
import com.ppc.utils.MinIoUtil;
import com.ppc.vo.TaskDetailVO;
import com.ppc.vo.TaskPageVO;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 工人任务相关接口
 *
 * @author Jeferry
 * @date 2023/12/20
 */
@Service
public class WorkerTaskServiceImpl implements WorkerTaskService {

  @Autowired
  private WorkerTaskMapper taskMapper;
  @Autowired
  private WorkerMapper workerMapper;
  @Autowired
  private MinIoUtil minIoUtil;
  @Autowired
  private FileMapper fileMapper;


  /**
   * 分页查询订单
   *
   * @param page       页码
   * @param pageSize   页大小
   * @param taskStatus 任务状态
   * @return {@link PageResult}
   */
  @Override
  public PageResult queryTaskWithStatus(Integer page, Integer pageSize, Integer taskStatus) {
    //只查询跟自己有关的订单
    Long userId = BaseContext.getCurrentId();
    Long currentWorkerId = workerMapper.getCurrentWorkerId(userId);
    PageHelper.startPage(page, pageSize);
    Page<TaskPageVO> p = taskMapper.pageQuery(taskStatus,currentWorkerId);
    return new PageResult(p.getTotal(), p.getResult());
  }

  /**
   * 分页查询订单（只含申诉）
   *
   * @param page 页码
   * @param pageSize 页大小
   * @return {@link PageResult}
   */
  @Override
  public PageResult queryTaskStatusIsClaim(Integer page, Integer pageSize) {
    //只查询跟自己有关的订单
    Long userId = BaseContext.getCurrentId();
    Long currentWorkerId = workerMapper.getCurrentWorkerId(userId);
    PageHelper.startPage(page, pageSize);
    Page<TaskPageVO> p = taskMapper.pageQueryOnlyClaim(currentWorkerId);
    return new PageResult(p.getTotal(), p.getResult());
  }

  @Override
  public Long uploadFile(MultipartFile file) {

    String originalFilename=file.getOriginalFilename();
    int lastIndexOf = originalFilename.lastIndexOf(".");
    String extension = originalFilename.substring(lastIndexOf+1);


    String objectName = minIoUtil.updateFileName(originalFilename);
    String filepath = minIoUtil.getFileUrl(objectName);

    try {
      minIoUtil.upload(objectName,file);
      //在file表添加一条
      File workerFile=File.builder()
          .fileName(originalFilename)
          .fileUrl(objectName)
          .fileType(extension)
          .build();

      fileMapper.insertFile(workerFile);

      return workerFile.getFileId();
    } catch (Exception e) {
      throw new FileException(MessageConstant.UPLOAD_FAILED);
    }


  }


  /**
   * 查看订单详情
   *
   * @param taskId 订单id
   * @return {@link TaskDetailVO}
   */
  @Override
  public TaskDetailVO queryTaskInformation(Long taskId) {
    TaskDetailVO taskDetailVO = taskMapper.queryTaskInformation(taskId);
//    String requireTagId = t.getRequireTag();
//    t.setRequireTag(taskMapper.selectTagById(Integer.valueOf(requireTagId)));
    if (taskDetailVO == null) {
      throw new BaseException("不存在该订单");
    }
    return taskDetailVO;
  }

  /**
   * 修改订单状态
   *
   * @param taskId     订单id
   * @param taskStatus 订单状态
   */
  @Override
  public void changeTaskStatus(Long taskId, Integer taskStatus) {
    taskMapper.changeTaskStatus(taskId, taskStatus);
  }

  /**
   * 提交订单文件(不涉及文件上传)
   *
   * @param taskId     订单id
   * @param fileIdList 文件id列表
   */
  @Override
  public void handinTask(Long taskId, List<Long> fileIdList) {
    for (Long fileId : fileIdList) {
      WorkerHandInResult result = WorkerHandInResult.builder().
          workerId(workerMapper.getCurrentWorkerId(BaseContext.getCurrentId())).
          taskId(taskId).
          fileId(fileId).
          createTime(LocalDateTime.now()).
          build();
      //调用mapper进行插入操作
      //先判断是不是已经在表中了，但是一般来说是不会的
      int answer = taskMapper.judgeHandin(taskId, fileId);
      if (answer == 0) {
        taskMapper.handinTask(result);
      } else {
        String message = taskId + "号订单已提交过";
        throw new BaseException(message);
      }
    }
  }

  /**
   * 给订单打分
   *
   * @param taskId 需求id
   * @param comment   打分
   */
  @Override
  public void commentTask(Long taskId, Integer comment) {
    //先根据taskid找到对应的requireid
    Long requireId=taskMapper.selectRequireId(taskId);
    //进行打分
    taskMapper.commentTask(requireId, comment);
    //根据分数去加减雇主的信誉分
    Long employerId = taskMapper.selectEmployerId(requireId);
    Long employerUserId = taskMapper.selectEmployerUserId(employerId);
    //找到原本的信誉
    Integer employerCredit = taskMapper.selectEmployerCredit(employerId);
    //加分 评价10分就变成信誉加5分
    employerCredit += comment - 5;
    if (employerCredit >= 100) {
      employerCredit = 100;
    } else if (employerCredit < 0) {
      employerCredit = 0;
    }
    taskMapper.changeEmployerCredit(employerId, employerCredit);
    //插入一条记录
    //2023-12-15 22:25:35.50 2612200 发布并完成 'VI设计' 订单,信誉度+5
    // 获取当前时间
    LocalDateTime now = LocalDateTime.now();
    // 定义日期时间格式
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    // 格式化LocalDateTime对象
    String formattedDateTime = now.format(formatter);
    String requirename = taskMapper.selectRequireName(requireId);
    String content = formattedDateTime + " 发布并完成" + requirename + "订单,信誉度";
    if (comment - 5 >= 0) {
      Integer realcomment = comment - 5;
      content += "+" + realcomment;
    } else if (comment - 5 < 0) {
      Integer realcomment = comment - 5;
      content += "-" + realcomment;
    }
    Recording record = Recording.builder().
        userId(employerUserId).
        recordingContent(content).
        recordingType(1).
        build();
    //插入到记录表中
    taskMapper.insertIntoRecording(record);
  }

  /**
   * 判断订单是否已经评分
   *
   * @param taskId 需求id
   * @return boolean
   */
  @Override
  public boolean ifTaskCommented(Long taskId) {
    Integer result = taskMapper.selectTaskCommented(taskId);
    if (result != null) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 查看已完成订单评分
   *
   * @param taskId 需求id
   * @return {@link Integer}
   */
  public Integer getEmployerRating(Long taskId) {

    Integer result = taskMapper.selectTaskCommented(taskId);
    Integer taskstatus = taskMapper.queryTaskStatus(taskId);
    if (taskstatus >= 2) {
      if (result == null) {
        throw new BaseException("订单还没有被评分");
      } else {
        return result;
      }
    } else {
      throw new BaseException("该订单还未完成");
    }
  }
}
